<template>
  <!-- 营销项目总结提报 -->
  <div>
    <!-- 搜索 -->
    <TopFilter
      :list="topFilterInit"
      :cols="3"
      labelWidth="110"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>

    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :isSelectColumn="isSelectColumn"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :onColumnsChange="columns => this.columns = columns"
      columnsRef="projectOperating_summary_report_index_01"
    ></FilterTable>

    <Drawer
      :visible.sync="visibleDrawer"
      title="项目总结提报"
      destroyOnClose
      :containerStyle="{width:'70vw',minWidth:'1000px',height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <info-modal v-model="initData" :rowData="formData" @close="drawerClose" />
    </Drawer>

    <!-- 选择方案 -->
    <BaseDialog
      title="选择项目"
      :visible.sync="visibleDialogPro"
      width="700px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <programModal selectType="single" @close="selectModelBackPro" />
    </BaseDialog>
    <!-- 选择车型 -->
    <BaseDialog
      title="选择车型"
      :visible.sync="visibleDialog"
      width="700px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <modalModal selectType="multiple" @close="selectModelBack" />
    </BaseDialog>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import infoModal from './info';
import programModal from '../../program/push/select';
import modalModal from '@/pages/cms-common/model/indexFilter';
import moment from 'moment';
import { formatdateByDay } from '@/utils/index';
import { getBigMarketType, getSmallMarketType, getSummaryDlrInquireList, selectListByBill } from '@/api/cms-api/projectOperating/plan/index';

export default {
  mixins: [dictionary],
  components: { infoModal, programModal, modalModal },
  data() {
    return {
      topFilterInit: this.topFilterInitFun(),
      columns: this.creatHeader(),
      fetchParams: { zj: 1 }, //参数
      fetchApi: getSummaryDlrInquireList, //ipa 接口
      isSelectColumn: false,
      initData: {},
      formData: {},
      visibleDrawer: false,
      visibleDialogPro: false,
      visibleDialog: false,
      projectProgramId: 0, //项目id
      modelIdList: [],
      modelName: ''
    };
  },
  methods: {
    //关闭详情
    drawerClose(val, type) {
      this.visibleDrawer = false;
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
    },
    //详情
    async drawerHandle(row, type) {
      let res = {};
      let res1 = {};
      let res2 = {};
      let res3 = {};
      let res4 = {};
      let res5 = {};
      let res6 = {};
      //逻辑自己写
      this.initData = {
        row: row,
        type: type //add/edit/show
      };
      this.formData = row;
      //现场高清照片
      let fileParams = { planId: this.formData.planId, billType: 25791001 };
      res = await selectListByBill(fileParams);
      if (res.data.length > 0) {
        let caseUrlList = [];
        for (let j = 0; j < res.data.length; j++) {
          let o1 = { name: res.data[j].fileName };
          let o2 = { url: res.data[j].fileId };
          let a = Object.assign(o1, o2);
          caseUrlList.push(a);
        }
        this.initData.row = Object.assign({}, { photoUrl: caseUrlList }, this.initData.row);
      }
      //项目核销材料
      let fileParams1 = { planId: this.formData.planId, billType: 25791002 };
      res1 = await selectListByBill(fileParams1);
      if (res1.data.length > 0) {
        let caseUrlList = [];
        for (let j = 0; j < res1.data.length; j++) {
          let o1 = { name: res1.data[j].fileName };
          let o2 = { url: res1.data[j].fileId };
          let a = Object.assign(o1, o2);
          caseUrlList.push(a);
        }
        this.initData.row = Object.assign({}, { cancellationUrl: caseUrlList }, this.initData.row);
      }
      //实际使用费用明细
      let fileParams2 = { planId: this.formData.planId, billType: 25791003 };
      res2 = await selectListByBill(fileParams2);
      if (res2.data.length > 0) {
        let caseUrlList = [];
        for (let j = 0; j < res2.data.length; j++) {
          let o1 = { name: res2.data[j].fileName };
          let o2 = { url: res2.data[j].fileId };
          let a = Object.assign(o1, o2);
          caseUrlList.push(a);
        }
        this.initData.row = Object.assign({}, { feeDetailUrl: caseUrlList }, this.initData.row);
      }
      //合同报价单
      let fileParams3 = { planId: this.formData.planId, billType: 25791004 };
      res3 = await selectListByBill(fileParams3);
      if (res3.data.length > 0) {
        let caseUrlList = [];
        for (let j = 0; j < res3.data.length; j++) {
          let o1 = { name: res3.data[j].fileName };
          let o2 = { url: res3.data[j].fileId };
          let a = Object.assign(o1, o2);
          caseUrlList.push(a);
        }
        this.initData.row = Object.assign({}, { contractOfferUrl: caseUrlList }, this.initData.row);
      }
      //发票
      let fileParams4 = { planId: this.formData.planId, billType: 25791005 };
      res4 = await selectListByBill(fileParams4);
      if (res4.data.length > 0) {
        let caseUrlList = [];
        for (let j = 0; j < res4.data.length; j++) {
          let o1 = { name: res4.data[j].fileName };
          let o2 = { url: res4.data[j].fileId };
          let a = Object.assign(o1, o2);
          caseUrlList.push(a);
        }
        this.initData.row = Object.assign({}, { billUrl: caseUrlList }, this.initData.row);
      }
      //报备附件
      let fileParams5 = { planId: this.formData.planId, billType: 25791006 };
      res5 = await selectListByBill(fileParams5);
      if (res5.data.length > 0) {
        let caseUrlList = [];
        for (let j = 0; j < res5.data.length; j++) {
          let o1 = { name: res5.data[j].fileName };
          let o2 = { url: res5.data[j].fileId };
          let a = Object.assign(o1, o2);
          caseUrlList.push(a);
        }
        this.initData.row = Object.assign({}, { uploadFileList: caseUrlList }, this.initData.row);
      }
      //其它
      let fileParams6 = { planId: this.formData.planId, billType: 25791007 };
      res6 = await selectListByBill(fileParams6);
      if (res6.data.length > 0) {
        let caseUrlList = [];
        for (let j = 0; j < res6.data.length; j++) {
          let o1 = { name: res6.data[j].fileName };
          let o2 = { url: res6.data[j].fileId };
          let a = Object.assign(o1, o2);
          caseUrlList.push(a);
        }
        this.initData.row = Object.assign({}, { otherUrl: caseUrlList }, this.initData.row);
      }
      this.visibleDrawer = true;
    },

    //日期格式化年月
    formatDatesNoDay: function(value) {
      // 这里的 value 就是需要过滤的数据
      if (value == null || value == '') {
        return '';
      }
      // var date = new Date(value);
      // var year = date.getFullYear();
      // var month = date.getMonth() + 1;
      return moment(value).format('YYYY-MM');
    },
    //日期格式化年月日
    formatDates: function(value) {
      // 这里的 value 就是需要过滤的数据
      if (value == null || value == '') {
        return '';
      }
      // var date = new Date(value);
      // var year = date.getFullYear();
      // var month = date.getMonth() + 1;
      // var day = date.getDate();
      return moment(value).format('YYYY-MM-DD'); //兼容ie
    },

    //实际开展/投放时间 改变方法
    initReleaseTimeSmall(val) {
      //清空 计划支持场次/投放天数、开始日期、结束日期

      this.initForm.find(item => item.fieldName === 'realTimeDay').initialValue = 0;
      this.initForm.find(item => item.fieldName === 'realStartDate').initialValue = '';
      this.initForm.find(item => item.fieldName === 'realEndDate').initialValue = '';
      // this.initForm.find(item => item.fieldName === 'projectFile').initialValue = vlue
      if (val != null && val.length > 0) {
        //如果计划开展/投放时间不为空
        //设置计划支持场次/投放天数为所选天的个数
        this.initForm.find(item => item.fieldName === 'realTimeDay').initialValue = val.length;
        let realStartDateTmp = '';
        let realEndDateTmp = '';
        //冒泡获取开始日期和结束日期
        for (let i = 0; i < val.length; i++) {
          if (!realStartDateTmp) {
            realStartDateTmp = val[i];
            realEndDateTmp = val[i];
          } else {
            if (realStartDateTmp > val[i]) {
              realStartDateTmp = val[i];
            }
            if (realEndDateTmp < val[i]) {
              realEndDateTmp = val[i];
            }
          }
        }
        this.initForm.find(item => item.fieldName === 'realStartDate').initialValue = formatdateByTime(realStartDateTmp);
        this.initForm.find(item => item.fieldName === 'realEndDate').initialValue = formatdateByTime(realEndDateTmp);
      }
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.drawerHandle(props.row, 'edit')}>
                  编辑
                </el-button>
              </div>
            );
          }
        },
        { title: '项目编号', dataIndex: 'planCode', sorter: true },
        {
          title: '项目状态',
          dataIndex: 'planStatus',
          sorter: true,
          render: props => {
            //编码转汉字
            return <span>{this.createDictText(props.row.planStatus, '2531')}</span>;
          }
        },
        { title: '计划项目金额', dataIndex: 'planProjectAmount', sorter: true, numberFormat: true },
        { title: '计划批准金额', dataIndex: 'planApproveAmount', sorter: true, numberFormat: true },
        {
          title: '计划核销比例',
          dataIndex: 'planCancellationRatio',
          sorter: true,
          render: props => {
            if (props.row.planCancellationRatio == null) {
              return <span slot="append">{props.row.planCancellationRatio}</span>;
            } else {
              return <span slot="append">{props.row.planCancellationRatio}%</span>;
            }
          }
        },
        { title: '实际项目金额', dataIndex: 'realProjectAmount', sorter: true, numberFormat: true },
        { title: '实际批准金额', dataIndex: 'realApproveAmount', sorter: true, numberFormat: true },
        {
          title: '实际核销比例',
          dataIndex: 'realCancellationRatio',
          sorter: true,
          render: props => {
            if (props.row.realCancellationRatio == null) {
              return <span slot="append">{props.row.realCancellationRatio}</span>;
            } else {
              return <span slot="append">{props.row.realCancellationRatio}%</span>;
            }
          }
        },
        {
          title: '合作方式',
          dataIndex: 'cooperationMethod',
          sorter: true,
          render: props => {
            //编码转汉字
            return <span>{this.createDictText(props.row.cooperationMethod, '2532')}</span>;
          }
        },
        { title: '计划支持场次/投放天数', dataIndex: 'planTimeDay', sorter: true },
        { title: '实际支持场次/投放天数', dataIndex: 'realTimeDay', sorter: true },
        { title: '目标订单数', dataIndex: 'targetOrderNum', sorter: true },
        { title: '目标集客数', dataIndex: 'targetGuestsNum', sorter: true },
        { title: '目标留档数', dataIndex: 'targetRetentionNum', sorter: true },
        { title: '实际订单数', dataIndex: 'realOrderNum', sorter: true },
        { title: '实际集客数', dataIndex: 'realGuestsNum', sorter: true },
        { title: '实际留档数', dataIndex: 'realRetentionNum', sorter: true },
        {
          title: '项目月份',
          dataIndex: 'activityMonth',
          sorter: true,
          render: props => {
            return <span>{this.formatDatesNoDay(props.row.activityMonth)}</span>;
          }
        },
        { title: '项目车型', dataIndex: 'modelLists', sorter: true },
        { title: '项目大类', dataIndex: 'projectMainClassName', sorter: true },
        { title: '项目小类', dataIndex: 'projectSmallClassName', sorter: true },
        { title: '项目名称', dataIndex: 'projectName', sorter: true },
        { title: '方案编号', dataIndex: 'programCode', sorter: true },
        { title: '方案名称', dataIndex: 'programName', sorter: true },
        {
          title: '开始日期',
          dataIndex: 'realStartDate',
          sorter: true,
          render: props => {
            return <span>{formatdateByDay(props.row.realStartDate)} </span>;
          }
        },
        {
          title: '结束日期',
          dataIndex: 'realEndDate',
          sorter: true,
          render: props => {
            return <span>{formatdateByDay(props.row.realEndDate)} </span>;
          }
        }
      ];
    },
    //取项目大类
    async initBigMarketType() {
      let res = [];
      let rd = await getBigMarketType();
      for (let i in rd.data) {
        res.push({ text: rd.data[i].typeName, value: rd.data[i].typeId });
      }
      this.topFilterInit[7].itemList = res;
    },
    //取项目小类
    async initMarketTypeSmall(parentTypeId) {
      let res = [];
      this.topFilterInit.find(item => item.fieldName === 'projectSmallClass').initialValue = '';
      this.topFilterInit.find(item => item.fieldName === 'projectSmallClass').itemList = [];
      if (parentTypeId != '') {
        this.dataParams = { parentTypeId: parentTypeId };
        let rd = await getSmallMarketType(this.dataParams);
        for (let i in rd.data) {
          res.push({ text: rd.data[i].typeName, value: rd.data[i].typeId });
        }
        this.topFilterInit[8].itemList = res;
      }
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    //搜索回调
    changeHandle(data) {
      //开始日期
      let realStartDate = data.realStartDate;
      //项目月份
      let activityMonth = data.activityMonth;
      data = Object.assign({}, { timestart: realStartDate[0] }, data);
      data = Object.assign({}, { timeend: realStartDate[1] }, data);
      data = Object.assign({}, { activityMonthStart: activityMonth[0] }, data);
      data = Object.assign({}, { activityMonthEnd: activityMonth[1] }, data);
      data = Object.assign({}, { zj: 1 }, data);
      data = Object.assign({ projectProgramId: this.projectProgramId, modelIdList: this.modelIdList }, data);
      this.modelIdList = '';
      this.projectProgramId = '';
      this.fetchParams = Object.assign({}, data);
    },
    //搜索数据
    topFilterInitFun() {
      return [
        {
          type: 'INPUT',
          label: '项目方案',
          fieldName: 'projectProgramName',
          placeholder: '请选择',
          initialValue: '',
          readonly: true,
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={() => this.openModelDialogPro()}></el-button>;
          }
        },
        {
          type: 'SELECT',
          label: '项目状态',
          fieldName: 'planStatus',
          placeholder: '请选择',
          initialValue: '',
          itemList: this.createDictListRemoveCodes('2531', ['25311001', '25311002', '25311003', '25311005', '25311006', '25311008', '25311009', '25311011', '25311012', '25311013'])
        },
        { type: 'INPUT', label: '项目编号', fieldName: 'planCode', placeholder: '请输入', initialValue: '' },
        { type: 'INPUT', label: '项目名称', fieldName: 'projectName', placeholder: '请输入', initialValue: '' },
        { type: 'RANGE_DATE', label: '项目执行开始日期', fieldName: 'realStartDate', initialValue: '', placeholder: '请选择' },
        { type: 'RANGE_DATE', label: '项目月份', fieldName: 'activityMonth', dateType: 'monthrange', initialValue: '', placeholder: '请选择' },
        {
          type: 'INPUT',
          label: '车型',
          fieldName: 'modal',
          placeholder: '请选择',
          initialValue: '',
          readonly: true,
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={() => this.openModelDialog()}></el-button>;
          }
        },
        {
          type: 'SELECT',
          label: '项目大类',
          fieldName: 'projectMainClass',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
          change: value => {
            this.initMarketTypeSmall(value);
          }
        },
        { type: 'SELECT', label: '项目小类', fieldName: 'projectSmallClass', placeholder: '请选择', initialValue: '', itemList: [] },
        { type: 'SELECT', label: '合作方式', fieldName: 'cooperationMethod', placeholder: '请选择', initialValue: '', itemList: this.createDictList('2532') }
      ];
    },
    //车型弹窗打开
    openModelDialog() {
      this.visibleDialog = true;
    },
    //车型弹窗关闭
    selectModelBack(data) {
      if (data && data.data && typeof data.data != null) {
        //清空数据
        this.modelIdList = '';
        this.modelName = '';
        //循环返回数据
        data.data.forEach(x => {
          //使用逗号分隔拼接车型ID
          if (this.modelIdList == '') {
            this.modelIdList = x.modelId;
          } else {
            this.modelIdList += ',' + x.modelId;
          }

          //使用逗号分隔拼接车型名称
          if (this.modelName == '') {
            this.modelName = x.modelName;
          } else {
            this.modelName += ',' + x.modelName;
          }
        });

        //显示车型名称
        this.topFilterInit[6].initialValue = this.modelName;
      }
      this.visibleDialog = false; //关闭弹窗
    },
    //项目方案弹窗打开
    openModelDialogPro() {
      this.visibleDialogPro = true;
    },
    //项目弹窗关闭
    selectModelBackPro(data) {
      // console.log('---data:', data);
      if (data && data.data && typeof data.data != null) {
        this.projectProgramId = data.data[0].projectProgramId;

        this.topFilterInit[0].initialValue = data.data[0].programName;
      }

      this.visibleDialogPro = false; //关闭弹窗
    }
  },
  mounted() {
    //初始化项目大类
    this.initBigMarketType();
  }
};
</script>

<style scoped>
</style>
